package org.example.controller;

import org.example.Entity.Result;
import org.example.Entity.User;
import org.example.service.UsersService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.example.utils.RegexValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户API
 */
@Validated
@RestController
@RequestMapping("/api/auth")
public class UserController {
 
    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")   //校验
    public Result register(@RequestBody User user){
        if (!RegexValidator.validate(user.getAccount(), "^1[0-9]{10}$") ||
                !RegexValidator.validate(user.getPassword(), "^\\S{5,16}$")){
            return Result.error("账号/密码不合规！");
        }
        //查询用户
        User ruser = usersService.findByAccount(user.getAccount());
        if (ruser == null){
            //注册
            usersService.register(user);
            //TODO 返回用户信息作用？如果没用是否可以删除
            return Result.success();
        }else {
            //占用
            return Result.error("账号已存在！");
        }

    }
    @PostMapping("/login")
    public Result<Map> login(@RequestBody User user){
        if (!RegexValidator.validate(user.getAccount(), "^1[0-9]{10}$") ||
                !RegexValidator.validate(user.getPassword(), "^\\S{5,16}$")){
            return Result.error("账号/密码不合规！");
        }

        //查询用户
        User loginUser = usersService.findByAccount(user.getAccount());

        //判断用户是否存在
        if (loginUser == null){
            return Result.error("账号错误！");
        }

        //判断密码是否正确 loginUser对象中password是密文
        if(Md5Util.getMD5String(user.getPassword()).equals(loginUser.getPassword())){
            //登录成功,生成Token
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getAccount());
            String token = JwtUtil.genToken(claims);
            //3.Jwt 生成 token 作为 key，账号作为值，保存到 redis 上
            redisTemplate.opsForValue().set(token,user.getAccount());
            Map<String ,String> userInfoMap = new HashMap();
            userInfoMap.put("uid",loginUser.getId().toString());
            userInfoMap.put("name",loginUser.getName());
            userInfoMap.put("token",token);
            return Result.success("ok",userInfoMap);
        }
        return Result.error("密码错误");
    }


    @PostMapping("/logout")
    public Result<String> logout(@RequestHeader(name = "Authorization") String token){
        //从 redis 删除token
        redisTemplate.delete(token);
        return Result.success();
    }
}